<?php
class BrandController extends BaseManageController{
	public function actionAdmin($id=null){
		$mod = new BrandModel();
		$con = array(
			'site_id' => SITE_ID
		);
		if($id != null){
			$con['cate'] = $id;
		}
		$total = $mod->count($con);
		$this->setPagination($total);
		$brands = $mod->find($con, 'main_picture,name,rank,cate,brand_flags', $this->pager->offset, $this->pager->pageSize, array('rank'=>1));
		$this->pageTitle = '品牌管理 - ' . Yii::app()->name;
		$this->render('admin', array('list'=>$brands));
	}
	
	public function actionEdit($id = null){
		if(Yii::app()->request->isPostRequest){
			$this->_save($id);
		}
		if($id == null){
			$brand = array(
				'_id' 	=> '',
				'rank' 	=> 255
			);
		}else{
			$mod = new BrandModel();
			$brand = $mod->get_by_key($id);
			if($brand['site_id'] != SITE_ID){
				throw new CHttpException(403, '非法请求！');
			}
		}
		$this->pageTitle = '品牌编辑 - ' . Yii::app()->name;
		$this->render('edit', array('model'=>$brand));
	}
	
	private function _save($id){
		if(!isset($_POST['Brand'])){
			$this->ajax_error('非法请求！');
		}
		$brand = $_POST['Brand'];

		//处理图片
		$this->init_pictures('brand/', $brand);
		
		CommonHelper::fix(BrandModel::$VALUE_TYPE, $brand);
		
		$mod = new BrandModel();
		if(empty($brand['_id'])){
			//新建
			$id = CommonHelper::gen_uuid();
			$brand['create_user_id'] = intval(Yii::app()->user->id);
			$brand['create_time'] = time();
			$brand['site_id'] = SITE_ID;
			$brand['_id'] = $id;
			$mod->insert($brand);
		}else{
			$mod->update_by_key($brand['_id'], $brand);
		}
// 		GoodsCateModel::cleanCache();
		$this->ajax_info('保存成功！', $id);
	}
}